package com.yunhe.merchants.task;

import com.yunhe.common.constant.TimeConsts;
import com.yunhe.merchants.constant.MyProjectConsts;
import com.yunhe.merchants.domain.MyProject;
import com.yunhe.merchants.service.IMyProjectService;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.scheduling.annotation.EnableScheduling;
import org.springframework.scheduling.annotation.Scheduled;
import org.springframework.stereotype.Component;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.RestController;

import javax.annotation.Resource;
import java.util.List;

/**
 * @Author: DongWenYu
 * @Date: 2021/5/11 9:37
 */
@RestController
@EnableScheduling
public class ProtectTimeScheduled {

    private static final Logger logger = LoggerFactory.getLogger(ProtectTimeScheduled.class);

    @Resource(name = "myProjectServiceImpl")
    IMyProjectService myProjectService;

    /**
     * 每日任务，开启保护期提醒，已过期的关闭保护期提醒
     *
     * @return void
     * @create 2021/5/12 9:40
     */
    @Scheduled(cron = "0 0 0 0/1 *  ?")
    @RequestMapping(value = "/protectTime",method = RequestMethod.POST)
    public void handle() {
        //开启保护期提醒
        List<MyProject> myProjects = myProjectService.selectProtectedRemind();
        for (MyProject p : myProjects) {
            Long lastTime = System.currentTimeMillis() - p.getProtectDate().getTime();//保护期持续时间
            long l = TimeConsts.month * 3 - TimeConsts.week;
            if (lastTime > l
                    && lastTime < TimeConsts.month * 3) {
                p.setProtectRemind(MyProjectConsts.BOOLEAN.Yes.value());
                logger.info("id:{},开启保护期", p.getId());
                myProjectService.update(p);
            }

        }
        //关闭保护期提醒
        List<MyProject> projects = myProjectService.selectProtectedExpire();
        for (MyProject myProject : projects) {
            Long lastTime = System.currentTimeMillis() - myProject.getProtectDate().getTime();//保护期持续时间
            if (lastTime >= TimeConsts.month * 3){
                myProject.setProtectRemind(MyProjectConsts.BOOLEAN.No.value());
                logger.info("id:{},关闭保护期", myProject.getId());
                myProjectService.update(myProject);
            }
        }
    }
}
